<template>
  <div class="training-page">
    <div class="header">
      <div class="info-section">
        <view class="title">主办单位：</view>
        <view>{{ organizer || '未获取到数据' }}</view>
        <view class="title">培训内容：</view>
        <view class="t_content">{{ trainingContent || '未获取到数据' }}</view>
      </div>
    </div>

    <div class="registration-form">
      <div class="form-group">
        <text class="star">*</text>
        <label>姓名：</label>
        <input 
          type="text" 
          id="name" 
          v-model="formData.name" 
          placeholder="请输入姓名"
        >
      </div>

      <div class="form-group">
        <text class="star">*</text>
        <label for="contact">联系方式：</label>
        <input 
          type="text" 
          id="contact" 
          v-model="formData.contact" 
          placeholder="请输入联系方式"
          @input="validateContact"
        >
      </div>

      <div class="form-group">
        <text class="star">*</text>
        <label>培训时间：</label>
        <view class="_form_item_input">
          <picker mode="selector" :range="trainingTimes" @change="selectTrainingTime">
            <view class="_picker_view">
              <text>{{ formData.trainingTime || '请选择时间' }}</text>
              <up-icon name="arrow-down" color="#9e9e9e" size="30"></up-icon>
            </view>
          </picker>
        </view>
      </div>

      <button class="submit-btn" @click="submitForm" :disabled="isLoading">
        {{ isLoading ? '提交中...' : '提交报名' }}
      </button>
    </div>
  </div>
</template>

<script>
import { getAllActivity } from '/api/activity.js'
import { signAdd } from '../../api/sign';

export default {
  data() {
    return {
      organizer: '',                // 主办单位
      trainingContent: '',          // 培训内容
      trainingTimes: [],            // 培训时间列表（日期范围）
      formData: {
        name: "",
        contact: "",
        trainingTime: ""
      },
      isLoading: false,
      activityId: null,
      userId: '',
      startDate: '',                // 活动开始时间
      endDate: ''                   // 活动结束时间
    };
  },
  onLoad(options) {
    this.activityId = options.activityId || null;
    this.userId = uni.getStorageSync('userInfo').userId || '';
    this.loadActivityData();
  },
  methods: {
    async loadActivityData() {
      try {
        this.isLoading = true;
        const res = await getAllActivity(0, this.userId);
        console.log('获取到的活动数据:', res);
        
        if (res.code == '200' && res.data) {
          // 解析活动数据
          const activity = Array.isArray(res.data) ? res.data[0] : res.data;
		  console.log(activity)
		  this.activityId = activity.activityId
          
          // 提取主办单位和培训内容
          this.organizer = this.extractField(activity, 'organizer');
          this.trainingContent = this.extractField(activity, 'trainingContent') || '无详细内容';
          
          // 提取活动开始时间和结束时间
          this.startDate = this.extractField(activity, 'activityBeginTime');
          this.endDate = this.extractField(activity, 'activityEndTime');
          
          // 处理培训时间，生成开始到结束的日期列表
          this.trainingTimes = this.generateDateRange(this.startDate, this.endDate);
        } else {
          uni.showToast({
            title: res.message || '获取活动信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取活动信息错误:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    },
    
    // 通用字段提取方法
    extractField(obj, field, defaultValue = null) {
      const fields = field.split('.');
      let value = obj;
      try {
        for (const f of fields) {
          if (value && value[f] !== undefined) {
            value = value[f];
          } else {
            value = null;
            break;
          }
        }
      } catch (e) {
        console.error(`字段提取错误: ${field}`, e);
        value = null;
      }
      return value === undefined || value === null ? defaultValue : value;
    },
    
    // 生成开始时间到结束时间的日期列表
    generateDateRange(start, end) {
      if (!start || !end) return ['暂无可用时间'];
      
      const startDate = new Date(start);
      const endDate = new Date(end);
      if (startDate > endDate) return ['时间范围无效'];
      
      const dateList = [];
      let currentDate = new Date(startDate);
      while (currentDate <= endDate) {
        dateList.push(currentDate.toLocaleDateString());
        currentDate.setDate(currentDate.getDate() + 1);
      }
      return dateList;
    },
    
    selectTrainingTime(e) {
      if (e && e.detail) {
        const index = e.detail.value;
        this.formData.trainingTime = this.trainingTimes[index];
      } else {
        console.error('事件对象格式不正确:', e);
      }
    },
    
    validateContact() {
      if (this.formData.contact.length > 11) {
        this.formData.contact = this.formData.contact.slice(0, 11);
      }
    },
    
    async submitForm() {
      // 表单验证
      const { name, contact, trainingTime } = this.formData;
	  console.log(this.formData)
      
      // 验证姓名
      if (!name.trim()) {
        uni.showToast({
          title: '请输入姓名',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 验证联系方式
      if (!contact) {
        uni.showToast({
          title: '请输入联系方式',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (contact.length !== 11) {
        uni.showToast({
          title: '联系电话必须为 11 位',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 验证培训时间
      if (!trainingTime) {
        uni.showToast({
          title: '请选择培训时间',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      try {
        this.isLoading = true;
        
        // 准备提交数据
        const submitData = {
          activityId: this.activityId,
          userId: this.userId,
          signName: name.trim(),           // 使用 formData.name 并去除空格
          signPhone: contact,
          createAt: trainingTime
        };
		console.log(submitData)
        
        // 调用API提交报名信息
       const res = await signAdd(submitData)
        
        if (res.code == '200') {
          uni.showToast({
            title: '报名成功！',
            icon: 'success',
            duration: 2000,
          });
          
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 2000);
        } else {
          uni.showToast({
            title: res.message || '报名失败，请重试',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交报名错误:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
	
    }
	},
	}
</script>

<style scoped>
/* 样式保持不变 */
.training-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  background-color: aliceblue;
}

.info-section {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-top: 15px;
}

.info-section p {
  margin: 8px 0;
}

.registration-form {
  background-color: #ffffff;
  border-radius: 8px;
  
}

.form-group {
  margin-bottom: 20px;
  padding: 10px;
}

.form-group label {
  display: inline-block;
  width: 100px;
  font-weight: bold;
}

.form-group input, 
.form-group select {
  width: 300px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group select {
  width: 320px;
}
.star{
  color: red;
}
.submit-btn {
  background-color: #af3005;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 70px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 10px;
  font-weight:900;
  width: 50%;
}

._form_item_input {
  display: inline-block;
  width: 320px;
  position: relative;
}

._picker_view {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 20px;
}

/* 确保图标样式正确显示 */
up-icon {
  display: inline-block;
}
.title {
  font-size: 20px;
  text-decoration: underline red; 
  font-weight: 700;
  
}
.t_content{
  color: darkgrey;
}
.t_location, .t_date {
  color: #555;
  margin-bottom: 5px;
}
</style>